package com.jh.user.service;

import cn.jh.common.exception.ParamValidationException;
import cn.jh.common.exception.ServiceException;
import cn.jh.common.pojo.BaseResponse;
import cn.jh.common.pojo.ValidationUtils;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.CommonsUtil;
import cn.jh.common.utils.TokenUtil;
import com.google.common.collect.ImmutableList;
import com.jh.user.business.*;
import com.jh.user.pojo.FastSilverPicPathRequest;
import com.jh.user.pojo.ShopRegister;
import com.jh.user.pojo.StoreInfo;
import com.jh.user.pojo.User;
import com.jh.user.pojo.enums.ShopRegisterStatusEnums;
import com.jh.user.pojo.validator.Create;
import com.jh.user.pojo.validator.Update;
import com.jh.user.pojo.validator.Verify;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.util.Base64Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
import static org.springframework.util.StringUtils.hasText;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;


@RestController
public class ShopRegisterService {

    private static final ImmutableList<String> ALLOW_IMAGES = ImmutableList.of("jpg", "png");
    private final Logger LOG = LoggerFactory.getLogger(ShopRegisterService.class);

    private final ShopRegisterBussiness shopRegisterBussiness;
    private final UserLoginRegisterBusiness userLoginRegisterBusiness;
    private final UserBusiness userBusiness;
    private final StoreInfoBussiness storeInfoBussiness;
    private final UserRoleResourceBusiness userRoleResourceBusiness;

    @Value("${shop.register_pay_rate}")
    String registerPatRate;

    @Value("${shop.write_img_path}")
    String writeImgPath; //写图片路径

    @Value("${shop.read_img_path}")
    String readImgPath;

    @Autowired
    public ShopRegisterService(
            ShopRegisterBussiness shopRegisterBussiness,
            UserLoginRegisterBusiness userLoginRegisterBusiness,
            UserBusiness userBusiness,
            StoreInfoBussiness storeInfoBussiness, UserRoleResourceBusiness userRoleResourceBusiness) {
        this.shopRegisterBussiness = shopRegisterBussiness;
        this.userLoginRegisterBusiness = userLoginRegisterBusiness;
        this.userBusiness = userBusiness;
        this.storeInfoBussiness = storeInfoBussiness;
        this.userRoleResourceBusiness = userRoleResourceBusiness;
    }

    /**
     * 分页查询下级商户
     */
    @RequestMapping(method = POST, value = "/v1.0/user/shop/find/{token}")
    public Object findPage(
            @PathVariable("token") String token,
            @RequestParam(value = "shopId", defaultValue = "", required = false) String shopId,
            @RequestParam(value = "shopName", defaultValue = "", required = false) String shopName,
            @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
            @RequestParam(value = "startTime", defaultValue = "1990/01/01", required = false) Date startTime,
            @RequestParam(value = "roleId", defaultValue = "3", required = false) long roleId,     //roleId:1系统管理2贴牌商3代理商

            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception ignored) {
            return CommonsUtil.returnError(CommonConstants.ERROR_TOKEN,"token无效");
        }
        User myuser = userLoginRegisterBusiness.findUserById(userId);
        if(roleId == 1){
            return CommonsUtil.returnOK(shopRegisterBussiness.findShopRegisterByWheres(shopId,shopName,phone,startTime,-1,null,pageable));
        }else if(roleId == 2){
            return CommonsUtil.returnOK(shopRegisterBussiness.findShopRegisterByWheres(shopId,shopName,phone,startTime,myuser.getBrandId(),null,pageable));
        }else {
            return CommonsUtil.returnOK(shopRegisterBussiness.findShopRegisterByWheres(shopId,shopName,phone,startTime,-1,myuser.getPhone(),pageable));
        }
    }

    /**
     * 分页查询 商户
     */
    @RequestMapping(method = GET, value = "/v1.0/user/shop/findVerifys")
    public Object findVerifyPages(
            @RequestParam(value = "shopId", defaultValue = "", required = false) String shopId,
            @RequestParam(value = "legalName", defaultValue = "", required = false) String legalName,
            @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
            @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
        return BaseResponse.success(shopRegisterBussiness.findByShopIdAndLegalNameAndCreateTimeLessThanAndCreateTimeGreaterThan(shopId, legalName, startTime, endTime,null, pageable));
    }

    /**
     * 分页查询 （未审核的）商户
     */
    @RequestMapping(method = GET, value = "/v1.0/user/shop/findVerify")
    public Object findVerifyPage(
            @RequestParam(value = "shopId", defaultValue = "", required = false) String shopId,
            @RequestParam(value = "shopid", defaultValue = "", required = false) String shopid,
            @RequestParam(value = "shopname", defaultValue = "", required = false) String shopname,
            @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
            @RequestParam(value = "legalName", defaultValue = "", required = false) String legalName,
            @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
            @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
//        return BaseResponse.success(shopRegisterBussiness.findByShopIdAndLegalNameAndCreateTimeLessThanAndCreateTimeGreaterThan(shopId, legalName, startTime, endTime, ShopRegisterStatusEnums.VERIFY.getValue(), pageable));
        return BaseResponse.success(shopRegisterBussiness.findByWhere(shopid, shopname, phone, ShopRegisterStatusEnums.VERIFY.getValue(), pageable));
    }

    /**
     * 单个商户查询
     */
    @RequestMapping(method = GET, value = "/v1.0/user/shop/findById")
    public Object findPage(@RequestParam(value = "id") Long id) {
        return BaseResponse.success(shopRegisterBussiness.findById(id));
    }

    /**
     * 根据商户注册手机号验证用户信息
     * @param mobilePhone
     * @return
     */
    @RequestMapping(method = POST, value = "/v1.0/user/shop/verifyMobilePhone")
    public Object verifyMobilePhone(@RequestParam(value = "mobilePhone") String mobilePhone) {
        LOG.info("商户注册手机号mobilePhone = " + mobilePhone);
        try {
            if (StringUtils.isEmpty(mobilePhone)) {
                return CommonsUtil.returnError("商户注册手机号为空");
            }
            User user = userBusiness.getByPhone(mobilePhone);
            if (null == user) {
                return CommonsUtil.returnError("用户未注册");
            }
            if (!"1".equals(user.getRealnameStatus())) {
                return CommonsUtil.returnError("用户未实名认证");
            }
            ShopRegister shopRegister = shopRegisterBussiness.findByMobilePhone(mobilePhone);
            if (null != shopRegister) {
                return CommonsUtil.returnError("商户已进件");
            }
        } catch (Exception e) {
            LOG.info("根据商户注册手机号验证用户信息异常" + e);
            e.getStackTrace();
            return CommonsUtil.returnError("根据商户注册手机号验证用户信息异常，请稍后再试");
        }
        return CommonsUtil.returnSuccess("商户注册手机号验证通过");
    }

    /**
     * APP商户进件
     * @param shopRegister
     * @param token
     * @return
     */
    @RequestMapping(method = POST, value = "/v1.0/user/shop/add/{token}")
    public Object addShopRegister(ShopRegister shopRegister,
                                  @PathVariable("token") String token) {
        LOG.info("商户进件传入值shopRegister : " + shopRegister.toString());
        long brandId;
        try {
            brandId = TokenUtil.getBrandid(token);
        } catch (Exception ex) {
            LOG.error("Obtain token exception: {}", ex.getMessage());
            return CommonsUtil.returnError("用户未登录");
        }

        //判断是否通过实名认证
        //if(!"1".equals(userLoginRegisterBusiness.queryUserById(userId).getRealnameStatus())){
        //    return CommonsUtil.returnError("保存失败，请先进行实名认证");
        //}
        try {
            ValidationUtils.validData(shopRegister, Create.class);

            User user = userBusiness.getByPhone(shopRegister.getMobilePhone());
            if (null == user) {
                return CommonsUtil.returnError("获取用户信息失败");
            }

            shopRegister.setBrandId(brandId);
            shopRegister.setPayRate(new BigDecimal(registerPatRate));
            shopRegister.setUserId(user.getId());
            shopRegister.resolveValidPicUrl();

            shopRegister = shopRegisterBussiness.mergeShopRegister(shopRegister);

            Integer status = shopRegister.getStatus();
            LOG.info("ShopRegister表中status = " + status);

            if (status == 1 || status == 2 || status == 5) {
                user.setShopsStatus(status == 1 ? "0" : (status == 2 ? "2" : "1"));
                userBusiness.updateShopStatus(user);
            }

            //StoreInfo storeInfo = StoreInfo.info(shopRegister);
            //storeInfoBussiness.saveStoreInfo(storeInfo);
            return CommonsUtil.returnOK(shopRegister);
        } catch (ServiceException | ParamValidationException ex) {
            return CommonsUtil.returnError(ex.getMessage());
        }
    }

    /**
     * 管理后台商户进件/修改
     * @param shopRegister
     * @param sfppRequest
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/shopRegister/purchase/{token}")
    public @ResponseBody Object purchase(@PathVariable String token, ShopRegister shopRegister, FastSilverPicPathRequest sfppRequest) {
        try {
            long sysUserId = TokenUtil.getUserId(token);
            if (sysUserId == 0) {
                return CommonsUtil.returnError("token无效！");
            }
            Map<String, Object> userRole = userRoleResourceBusiness.queryUserRole(sysUserId);
            long roleId = Long.parseLong(userRole.get("roleId") + "");
            if (roleId != 1) {
                // 系统管理员
                return CommonsUtil.returnError("非系统管理员，无法进行商户进件！");
            }
            Map<String, Object> map = shopRegisterBussiness.manageBankgroundPurchase(shopRegister, sfppRequest);
            return CommonsUtil.returnSuccess("进件成功！", map);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 商户进件修改
     * @param shopRegister
     * @param token
     * @return
     */
    @RequestMapping(method = POST, value = "/v1.0/user/shop/update/{token}")
    public Object updateShopRegister(ShopRegister shopRegister, @PathVariable("token") String token) {
        LOG.info("商户进件修改shopRegister：" + shopRegister.toString());
        //ValidationUtils.validData(shopRegister, Create.class);
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return BaseResponse.error("用户未登录");
        }
        try {
            ValidationUtils.validData(shopRegister, Update.class);

            //resolveValidPicUrl(shopRegister);
            //keepActivePic(shopRegister); 移至接口里面处理

            shopRegister.setStatus(1);
            ShopRegister sr = shopRegisterBussiness.update(shopRegister);

            // ShopRegister sr = shopRegisterBussiness.findById(shopRegister.getId());

            // 更新t_user表中商铺状态信息
            User user = userBusiness.getByPhone(sr.getMobilePhone());
            if (null != user) {
                Integer status = sr.getStatus();
                if (status == 1 || status == 2 || status == 5) {
                    user.setShopsStatus(status == 1 ? "0" : (status == 2 ? "2" : "1"));
                    userBusiness.updateShopStatus(user);
                }
            }

            storeInfoBussiness.updateStoreInfo(shopRegister);

            return CommonsUtil.returnOK();
        } catch (ServiceException | ParamValidationException ex) {
            return CommonsUtil.returnError(ex.getMessage());
        } catch (Exception ex) {
            LOG.error("FreeQuickServiceImpl.updateShopRegister,商户注册修改userId====" + userId +",异常====", ex.getMessage());
            return CommonsUtil.returnError("商户注册修改失败！");
        }
    }

    /**
     * 商户审核
     * @param request
     * @param shopRegister
     * @return
     */
    @RequestMapping(method = POST, value = "/v1.0/user/shop/verify")
    public Object verify(HttpServletRequest request,
                         ShopRegister shopRegister) {
        ValidationUtils.validData(shopRegister, Verify.class);
        shopRegister = shopRegisterBussiness.update(shopRegister);

        if (shopRegister.getStatus() == 5) {
            //审核通过，增加商户门店信息
            StoreInfo storeInfo = StoreInfo.info(shopRegister);
            storeInfoBussiness.saveStoreInfo(storeInfo, shopRegister.getBrandId());
        }
        /** 更新t_user表中商铺状态值 */
        User user = userBusiness.getByPhone(shopRegisterBussiness.findById(shopRegister.getId()).getMobilePhone());
        if (null != user) {
            Integer status = shopRegister.getStatus();
            LOG.info("ShopRegister表中status = " + status);
            if (status == 1) {
                user.setShopsStatus("0");
            } else if (status == 2) {
                user.setShopsStatus("2");
            } else if (status == 5) {
                user.setShopsStatus("1");
            }
            userBusiness.updateShopStatus(user);
        }

        return BaseResponse.success();
    }

    // 图片上传时写入图片的 Path，返回 null 表示创建目录失败
    @Nullable
    Path uploadWritePath() {
        String dateNow = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
        Path datePath = Paths.get(writeImgPath, dateNow);
        if (!Files.exists(datePath)) {
            try {
                Files.createDirectory(datePath);
            } catch (IOException ex) {
                // 创建目录失败（可能的原因：服务器目录没有写权限）
                LOG.error("Create directory {} is failure", datePath);
                return null;
            }
        }
        return datePath;
    }

    String getViewUrl(String relativePath) {
        String baseUrl = readImgPath.endsWith("/") ?
                readImgPath.substring(0, readImgPath.length() - 1) : readImgPath;
        String second = relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
        if ("\\".equals(System.getProperty("file.separator"))) {
            second = second.replaceAll("[\\\\]", "/");
        }
        return String.join("/", baseUrl, second);
    }

    @PostMapping(value = "/v1.0/user/shop/img/uploads")
    public Map<String, Object> uploadImages(
            HttpServletRequest servletRequest, @RequestParam("phone") String phone) {
        if (!(servletRequest instanceof MultipartHttpServletRequest)) {
            return BaseResponse.error("请选择要上传的图片").toMap();
        } else if (!hasText(phone)) {
            return BaseResponse.error("请确定上传图片属主").toMap();
        }
        Path writeDirPath = uploadWritePath();
        if (writeDirPath == null) { // 创建目录失败
            return BaseResponse.error("服务器发生错误，暂时不提供上传图片功能。").toMap();
        }
        MultipartHttpServletRequest request = (MultipartHttpServletRequest) servletRequest;

        if (LOG.isTraceEnabled()) {
            Iterator<String> fileNames = request.getFileNames();
            if (fileNames != null) {
                StringBuilder sb = new StringBuilder();
                while (fileNames.hasNext()) {
                    sb.append(fileNames.next()).append(",");
                }
                sb.deleteCharAt(sb.length() - 1);
                LOG.trace("Uploads fileNames: {}", sb.toString());
            }

        }

        String businessRelPath = writeUploadImage(request, writeDirPath, "business", phone);
        String legalIdRelPath = writeUploadImage(request, writeDirPath, "legalId", phone);
        String legalIdBackRelPath = writeUploadImage(request, writeDirPath, "legalIdBack", phone);
        String shopHeadRelPath = writeUploadImage(request, writeDirPath, "shopHead", phone);
        String firstRelPath = writeUploadImage(request, writeDirPath, "first", phone);
        String accountRelPath = writeUploadImage(request, writeDirPath, "account", phone);
        String bankFrontRelPath = writeUploadImage(request, writeDirPath, "bankFront", phone);
        String bankReverseRelPath = writeUploadImage(request, writeDirPath, "bankReverse", phone);
        String mchSceneRelPath = writeUploadImage(request, writeDirPath, "mchScene", phone);
        Map<String, Object> result = new HashMap<>(9);
        resolveViewUrl(result, "business", businessRelPath);
        resolveViewUrl(result, "legalId", legalIdRelPath);
        resolveViewUrl(result, "legalIdBack", legalIdBackRelPath);
        resolveViewUrl(result, "shopHead", shopHeadRelPath);
        resolveViewUrl(result, "first", firstRelPath);
        resolveViewUrl(result, "account", accountRelPath);
        resolveViewUrl(result, "bankFront", bankFrontRelPath);
        resolveViewUrl(result, "bankReverse", bankReverseRelPath);
        resolveViewUrl(result, "mchScene", mchSceneRelPath);

        LOG.info("/v1.0/user/shop/img/uploads返回图片地址：" + result.toString());
        return BaseResponse.success(result).toMap();
    }

    private void resolveViewUrl(Map<String, Object> result, String fieldName, String relPath) {
        if ("empty".equals(relPath) || "error".equals(relPath)) {
            result.put(fieldName, relPath);
        } else {
            result.put(fieldName, getViewUrl(relPath));
        }
    }

    String writeUploadImage(
            MultipartHttpServletRequest request, Path writeDirPath,
            String fieldName, String phone) {
        MultipartFile file = request.getFile(fieldName);
        if (file == null) {
            LOG.trace("Uploads `{}` file is null. Will be return `empty`", fieldName);
            return "empty";
        }
        // build write image file name
        String suffix = Base64Utils.encodeToUrlSafeString(
                Hex.decode(UUID.randomUUID().toString()
                .replaceAll("-", ""))).replaceAll("=", "");
        String originalName = file.getOriginalFilename();
        String extName = "jpg";
        if (originalName != null && originalName.contains(".")) {
            extName = FilenameUtils.getExtension(originalName);
            if (!ALLOW_IMAGES.contains(extName)) {
                LOG.error("Uploads file `{}` is not supported.", originalName);
                return "error";
            }
        }

        String fileName = String.join("", phone, "_", suffix, ".", extName);
        Path filePath = writeDirPath.resolve(fileName);

        try (InputStream inputStream = file.getInputStream()) {
            byte[] writeData = IOUtils.toByteArray(inputStream);

            Files.write(filePath, writeData, CREATE, WRITE);

            return writeDirPath.getFileName().resolve(fileName).toString();
        } catch (IOException ex) {
            LOG.error("上传的文件保存时发生 I/O 错误：{}, Will be return `error` for {}",
                    ex.getMessage(), fieldName);
            return "error";
        }
    }

    /**
     * 商户图片上传接口（前台调用）
     * @deprecated use {@link #uploadImages(HttpServletRequest, String)}
     */
//    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/shop/img/uploads")
    @Deprecated
    public Object imgUploads(HttpServletRequest request, @RequestParam("phone") String phone) {
        boolean fileexist = false;
        boolean picexist = false;
        HashMap<Object, Object> map = new HashMap<>();

        /* 先创建文件夹*/
        File dir = new File(readImgPath + phone);
        // 创建目录
        if (!dir.exists()) {
            LOG.info("=====创建目录" + readImgPath + phone + "成功！");
            dir.mkdir();
        } else {
            LOG.info("=====目录已存在");
            dir.delete();
            dir.mkdir();
            fileexist = true;
        }

        MultipartHttpServletRequest multipartRequest = null;
        try {
            multipartRequest = (MultipartHttpServletRequest) request;
        } catch (ClassCastException e) {
            LOG.info("=====phone:" + phone + "=====未传入任何图片：" + e);
            return CommonsUtil.returnError("未传入任何图片");
        } catch (Exception e) {
            LOG.info("=====phone:" + phone + "=====错误信息：" + e);
            return CommonsUtil.returnError("图片上传失败");
        }
        /*  MultipartFile files;*/

        InputStream is;
        FileOutputStream os;
        int i = 0;
        /*business图片上传*/
        MultipartFile business = multipartRequest.getFile("business");
        if (business != null) {
            try {
                map.put("business", readImgPath + "/" + phone + "/" + business.getOriginalFilename());
                //File dest = new File(readImgPath + "/" + phone + "/" + business.getOriginalFilename());
                //business.transferTo(dest);
                is = multipartRequest.getFiles("business").get(0).getInputStream();
                os = new FileOutputStream(writeImgPath + "/" + phone + "/" + business.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "=====ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("business上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "=====ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("business上传图片失败！");
            }
        } else {
            map.put("business", "business");
        }
        /* legalId图片上传*/
        MultipartFile legalId = multipartRequest.getFile("legalId");
        if (legalId != null) {
            try {
                map.put("legalId", readImgPath + "/" + phone + "/" + legalId.getOriginalFilename());
                //File dest1 = new File(readImgPath + "/" + phone + "/" +legalId.getOriginalFilename());
                //legalId.transferTo(dest1);
                is = legalId.getInputStream();
                os = new FileOutputStream(writeImgPath +"/" + phone + "/" + legalId.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("legalId上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("legalId上传图片失败！");
            }
        } else {
            map.put("legalId", "legalId");
        }


        /* legalIdBack图片上传*/
        MultipartFile legalIdBack = multipartRequest.getFile("legalIdBack");
        if (legalIdBack != null) {
            try {
                map.put("legalIdBack", readImgPath + "/" + phone + "/" + legalIdBack.getOriginalFilename());
                //File dest1 = new File(readImgPath + "/" + phone + "/" +legalId.getOriginalFilename());
                //legalId.transferTo(dest1);
                is = legalIdBack.getInputStream();
                os = new FileOutputStream(writeImgPath +"/" + phone + "/" + legalIdBack.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("legalIdBack上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("legalIdBack上传图片失败！");
            }
        } else {
            map.put("legalIdBack", "legalIdBack");
        }

        /*shopHead图片上传*/
        MultipartFile shopHead = multipartRequest.getFile("shopHead");
        if (shopHead != null) {
            try {
                map.put("shopHead", readImgPath + "/" + phone + "/" + shopHead.getOriginalFilename());
                //File dest1 = new File(readImgPath + "/" + phone + "/" +legalId.getOriginalFilename());
                //legalId.transferTo(dest1);
                is = shopHead.getInputStream();
                os = new FileOutputStream(writeImgPath +"/" + phone + "/" + shopHead.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("shopHead上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("shopHead上传图片失败！");
            }
        } else {
            map.put("shopHead", "shopHead");
        }

        /*first图片上传*/
        MultipartFile first = multipartRequest.getFile("first");
        if (first != null) {
            try {
                map.put("first", readImgPath + "/" + phone + "/" + first.getOriginalFilename());
                //File dest1 = new File(readImgPath + "/" + phone + "/" +legalId.getOriginalFilename());
                //legalId.transferTo(dest1);
                is = first.getInputStream();
                os = new FileOutputStream(writeImgPath +"/" + phone + "/" + first.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("first上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("first上传图片失败！");
            }
        } else {
            map.put("first", "first");
        }

        /*account图片上传*/
        MultipartFile account = multipartRequest.getFile("account");
        if (account != null) {
            try {
                map.put("account", readImgPath + "/" + phone + "/" + account.getOriginalFilename());
                //File dest1 = new File(readImgPath + "/" + phone + "/" +legalId.getOriginalFilename());
                //legalId.transferTo(dest1);
                is = account.getInputStream();
                os = new FileOutputStream(writeImgPath +"/" + phone + "/" + account.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("account上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("account上传图片失败！");
            }
        } else {
            map.put("account", "account");
        }
        /*银行卡正面bankFront图片上传*/
        MultipartFile bankFront = multipartRequest.getFile("bankFront");
        if (bankFront != null) {
            try {
                map.put("bankFront", readImgPath + "/" + phone + "/" + bankFront.getOriginalFilename());
                //File dest1 = new File(readImgPath + "/" + phone + "/" +legalId.getOriginalFilename());
                //legalId.transferTo(dest1);
                is = bankFront.getInputStream();
                os = new FileOutputStream(writeImgPath +"/" + phone + "/" + bankFront.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("bankFront上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("bankFront上传图片失败！");
            }
        } else {
            map.put("bankFront", "bankFront");
        }
        /*银行卡反面bankReverse图片上传*/
        MultipartFile bankReverse = multipartRequest.getFile("bankReverse");
        if (bankReverse != null) {
            try {
                map.put("bankReverse", readImgPath + "/" + phone + "/" + bankReverse.getOriginalFilename());
                //File dest1 = new File(readImgPath + "/" + phone + "/" +legalId.getOriginalFilename());
                //legalId.transferTo(dest1);
                is = bankReverse.getInputStream();
                os = new FileOutputStream(writeImgPath +"/" + phone + "/" + bankReverse.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("bankReverse上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("bankReverse上传图片失败！");
            }
        } else {
            map.put("bankReverse", "bankReverse");
        }
        /*商户场景mchScene图片上传*/
        MultipartFile mchScene = multipartRequest.getFile("mchScene");
        if (mchScene != null) {
            try {
                map.put("mchScene", readImgPath + "/" + phone + "/" + mchScene.getOriginalFilename());
                //File dest1 = new File(readImgPath + "/" + phone + "/" +legalId.getOriginalFilename());
                //legalId.transferTo(dest1);
                is = mchScene.getInputStream();
                os = new FileOutputStream(writeImgPath +"/" + phone + "/" + mchScene.getOriginalFilename());
                i = 0;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
                is.close();
                picexist = true;
            } catch (IllegalStateException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IllegalStateException=" + e);
                return CommonsUtil.returnError("mchScene上传图片失败！");
            } catch (IOException e) {
                LOG.error("=====phone:" + phone + "ShopRegisterService.imgUpload,上传图片异常IOException=" + e);
                return CommonsUtil.returnError("mchScene上传图片失败！");
            }
        } else {
            map.put("mchScene", "mchScene");
        }

        if (!picexist) {
            return BaseResponse.error("并未上传任何图片");
        }
        if (fileexist) {
            return BaseResponse.successfileexist(map);
        }
        LOG.info("=====map:" + map);
        return BaseResponse.success(map);
    }


    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/shop/img/upload")
    public Object imgUpload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile multipartFile = multipartRequest.getFiles("image").get(0);
        String fileName = System.currentTimeMillis() + new Random().nextInt(10) + ".jpg";
        File file = new File(writeImgPath + fileName);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            return BaseResponse.error("图片上传失败");
        }
        return BaseResponse.success(readImgPath + fileName);
    }

    /**
     * 查询商户信息
     * @return
     */
    @RequestMapping(method = GET, value = "/v1.0/user/shop/findByShopId/{token}")
    public Object findByShopId(@RequestParam(value = "shopId") String shopId, @PathVariable("token") String token) {
        try {
            long userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            LOG.error("查询商户信息ShopRegisterService.findByShopId-token无效");
            return CommonsUtil.returnError("token无效");
        }
        Map<String, Object> map = shopRegisterBussiness.queryByMobilePhone(shopId);
        return CommonsUtil.returnSuccess("查询成功！", map);
    }

    public Object findByShopId(
            @PathVariable("token") String token) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception ignored) {
            return CommonsUtil.returnError(CommonConstants.ERROR_TOKEN,"token无效");
        }
        ShopRegister shopRegister = shopRegisterBussiness.findByUserId(userId);
        if(shopRegister == null){
            shopRegister = new ShopRegister();
            shopRegister.setStatus(0);
            return CommonsUtil.returnSuccess("成功",shopRegister);
        }
        return BaseResponse.success(shopRegister);
    }


    /**
     * 更新商户信息（适用于支付配置信息更新）
     * @param shopRegister
     * @return
     */
    @RequestMapping(method = POST, value = "/v1.0/user/shop/updateShopRegister")
    public Object updateShopRegister(ShopRegister shopRegister){
        try {
            shopRegisterBussiness.updateShopRegister(shopRegister);
            return CommonsUtil.returnSuccess("");
        }catch (Exception e){
            LOG.error("ShopRegisterService.updateShopRegister，更新商户表异常======" + e.getMessage());
            return CommonsUtil.returnError("更新商户表失败！");
        }
    }

    /**
     * 商户关联支付配置信息
     */
    @RequestMapping(method = POST, value = "/v1.0/user/shop/associate")
    public Object associatePayConfigure(@RequestParam(value = "shopId") String shopId,
                                        @RequestParam(value = "alipayAppId", required = false) String alipayAppId,
                                        @RequestParam(value = "wechatAppId", required = false) String wechatAppId) {
        try {
            shopRegisterBussiness.updateShopPayConfigure(shopId, alipayAppId, wechatAppId);
        } catch (ServiceException ex) {
            return CommonsUtil.returnError(ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            return CommonsUtil.returnError("关联支付配置信息系统异常");
        }
        return CommonsUtil.returnOK();
    }

    /**
     * 商户关联支付配置补充
     * <p>比如支付宝授权成功，但同步ShopRegister时异常，可以通过这个接口补充同步</p>
     */
    @RequestMapping(method = POST, value = "/v1.0/user/shop/supply_config")
    public Object supplyPayConfigure(@RequestParam(value = "shopId") String shopId,
                                     @RequestParam(value = "alipayAppId", required = false) String alipayAppId,
                                     @RequestParam(value = "wechatAppId", required = false) String wechatAppId) {
        try {
            shopRegisterBussiness.supplyShopPayConfigure(shopId, alipayAppId, wechatAppId);
        } catch (ServiceException ex) {
            return CommonsUtil.returnError(ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            return CommonsUtil.returnError("关联支付配置信息系统异常");
        }
        return CommonsUtil.returnOK();
    }

    /**
     * 获取商户信息
     * @param userId
     * @param shopName
     * @param shopPhone
     * @return
     * {
     *     "result": {
     *         "userIds": "882204580"
     *     },
     *     "resp_message": "查询商户信息成功！",
     *     "resp_code": "000000"
     * }
     * {
     *     "resp_message": "非台卡代理无法查看商铺交易信息！",
     *     "resp_code": "999999"
     * }
     */
    @PostMapping(value = "/v1.0/user/shop/getUsernInfoByShopRegister")
    public @ResponseBody Object getUsernInfoByShopRegister(@RequestParam(value = "userId") long userId,
                                                           @RequestParam(value = "shopName", defaultValue = "", required = false) String shopName,
                                                           @RequestParam(value = "shopPhone", defaultValue = "", required = false) String shopPhone
                                                           ) {
        if (StringUtils.isEmpty(shopName) && StringUtils.isEmpty(shopPhone)) {
            return CommonsUtil.returnError("商户姓名和商户手机号为空！");
        }
        try {
            String userIds = shopRegisterBussiness.getUsernInfoByShopRegister(userId, shopName, shopPhone);
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("userIds", userIds);
            return CommonsUtil.returnSuccess("查询商户信息成功！", resMap);
        } catch (ServiceException e) {
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 根据shopId获取商户信息
     * @param shopId
     * @return
     */
    @PostMapping(value = "/v1.0/user/shopregister/getshopregisterbyshopid")
    public @ResponseBody Object getShopRegisterByShopId(String shopId) {
        try {
            Map<String, String> map = shopRegisterBussiness.getShopRegisterByShopId(shopId);
            return CommonsUtil.returnSuccess("商户信息获取成功！", map);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 获取商户信息
     * @param token
     * @return
     */
    @PostMapping(value = "/v1.0/user/shopregister/getbytoken/{token}")
    public @ResponseBody Object getByToken(@PathVariable String token) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效！");
        }
        try {
            Map<String, Object> map = shopRegisterBussiness.getShopRegisterByUserId(userId);
            return CommonsUtil.returnSuccess("查询成功！", map);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

}